package com.tom.architect.party5.day38.simple6.base;

import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;

import com.tom.architect.party5.day38.simple6.inject.InjectPresenter;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * Added by Tom on 2024/09/30.
 * MVP Activity 基类
 */
public abstract class BaseMvpActivity<P extends BasePresenter>
        extends AppCompatActivity
        implements BaseView {
    private P mPresenter;
    private List<BasePresenter> mPresenters; // 存起来，用于onDestroy detach

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView();
        mPresenters = new ArrayList<>();

        // 创建P，创建交给子类，每个Activity不一样。
        mPresenter = createPresenter();
        mPresenter.attach(this);

        // 自己实现：IOC 注入Presenter。通过反射/Dagger，实现注入。
        Field[] fields = getClass().getDeclaredFields();
        for (Field field : fields) {
            InjectPresenter injectPresenter = field.getAnnotation(InjectPresenter.class);
            if (injectPresenter != null) {
                // 创建注入
                Class<? extends BasePresenter> presenterClazz = null;
                try {
                    // TODO 添加判断类型，instanceOf？ 获取它的父类，如果不是继承自BasePresenter，就抛异常。
                    // TextView 添加注入后，这里不会进入异常代码。
                    presenterClazz = (Class<? extends BasePresenter>) field.getType();
                } catch (Exception e) {
                    // 其他的注入，
                    throw new RuntimeException("No Support inject Presenter type: " + field.getType().getName());
                }
                try {
                    BasePresenter basePresenter = presenterClazz.newInstance();
                    basePresenter.attach(this); // 去哪里解绑？
                    field.setAccessible(true);
                    // 设置子类中，mPresenter的值
                    field.set(this, basePresenter);
                    mPresenters.add(basePresenter); // 便于解绑
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        initView();
        initData();
    }


    // 子类自己实现 P的创建
    protected abstract P createPresenter();

    protected abstract void initData();

    protected abstract void initView();

    protected abstract void setContentView();

    @Override
    public void onDestroy() {
        super.onDestroy();
        for (BasePresenter presenter : mPresenters) {
            presenter.detach(); // 解绑 IOC创建的P。
        }
        mPresenter.detach();
    }

    public P getPresenter() {
        return mPresenter;
    }
}
